<template>
  <div v-loading="loading"  element-loading-text="加载中。。。">
    <el-card style="overflow:visible;">
      <el-form :model="form" size="mini" label-position="top" ref="form">
        <el-row :gutter="10">
            <el-col  :lg="4" :md="6">
              <el-form-item label="用户编号"  prop="ID" >
                <el-input v-model="form.ID" placeholder="请输入用户编号（工号）"></el-input>
              </el-form-item>
            </el-col>
            <el-col   :lg="4" :md="6">
              <el-form-item label="用户名称" prop="name">
                <el-input v-model="form.name"
                  placeholder="请输入用户名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col  :lg="4" :md="6">
                <el-form-item label="机构"  prop="branchId">
                   <select-tree :single-check="true" v-model="form.branchId"  style="width:170px;" :props='{id:"orgno",label: "cname",children: "children"}' :tree-data="brnoList"  placeholder="请选择机构"></select-tree>
                </el-form-item>
            </el-col>
            <!-- <el-col   :lg="4" :md="6">
              <el-form-item label="用户类型" prop="usertype">
                <el-select v-model="form.usertype" placeholder="选择用户类型">
                      <el-option v-for="item in usertypeList" :key="item.value" :label="item.label" :value="item.value">
                      </el-option>
                    </el-select>
              </el-form-item>
            </el-col> -->
            <el-col :lg='2' :md='3' class="searchBtnMarginTop">
                <el-button type="primary" icon='el-icon-search'
                  @click="checkUserList()"
                  :loading="loading" size='mini'>查询</el-button>
            </el-col>
            <el-col  :lg="2" :md="3" class="searchBtnMarginTop">
              <el-button type='warning' size='mini' icon='el-icon-refresh'
              @click="resetForm('form')">重置</el-button>
            </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card style="margin-top:10px;">
      <el-row :gutter="10">
        <el-col  :lg="2" :md="3" v-if="btnPermission('Button_User_Add')">
          <el-button type="primary" size="mini"  @click="createUser" icon='el-icon-plus'
          >新增</el-button>
        </el-col>
        <el-col  :lg="2" :md="3"  v-if="btnPermission('Button_User_Edit')">
          <el-button type="primary"
            size="mini" icon='el-icon-edit' @click="modUser" :disabled="!checkedUser"
            >修改</el-button>
        </el-col>
        <el-col :lg="2" :md="3" v-if="!btnPermission('Button_User_Delete')">
          <el-button type="danger"
            size="mini" @click="delUser" icon='el-icon-delete'  :disabled="!checkedUser"
          >删除</el-button>
        </el-col>
          <el-col  :lg="2" :md="3" >
            <el-dropdown trigger="click"  @command="handleCommand" >
              <el-button type="primary" size="mini" :disabled="!checkedUser">
                更多操作<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="systemUser" v-if="btnPermission('Button_User_Branch')">用户应用分配</el-dropdown-item>
                <el-dropdown-item command="casherPost" v-if="btnPermission('Button_User_Branch')">柜员岗位设置</el-dropdown-item>
                <!-- <el-dropdown-item command="branchDistribution" v-if="btnPermission('Button_User_Branch')">业务机构分配</el-dropdown-item> -->
                <el-dropdown-item command="changBranch" v-if="btnPermission('Button_User_Branch_Change')">机构调动</el-dropdown-item>
                <el-dropdown-item command="unlock" v-if="btnPermission('Button_User_Unlock')">解锁</el-dropdown-item>
                <el-dropdown-item @click.native="handleResetPassword" v-if="btnPermission('Button_User_ResetPwd')">重置密码</el-dropdown-item>
                <!-- <el-dropdown-item command="detailDev" v-if="btnPermission('Button_User_Detail')">详细信息</el-dropdown-item>
                <el-dropdown-item command="startDialogVisible" v-if="btnPermission('Button_User_CHistory')">自助C端操作记录查看</el-dropdown-item>
                <el-dropdown-item command="devRemove" v-if="btnPermission('Button_User_VHistory')">自助V端操作记录查看</el-dropdown-item>                     -->
              </el-dropdown-menu>
            </el-dropdown>
          </el-col>
      </el-row>
      <el-table :data="tableDataPage" ref="table" border class="tableMarginTop"
        highlight-current-row
        @selection-change="handleCurrentChange"
        header-row-class-name="tableHeaderClass"
        style="min-height:390px;">
        <el-table-column type="selection" width="40px"></el-table-column>
        <el-table-column prop="UserID" label="用户编号">
          <template slot-scope="scope">
              {{scope.row.UserNum}}
          </template>
        </el-table-column>
        <el-table-column prop="UserName" label="用户名称"></el-table-column>
        <el-table-column prop="UserStatus"  :formatter="dataFormat" label="用户状态"></el-table-column>
        <el-table-column prop="BranchNum" label="所在机构号"></el-table-column>
        <el-table-column prop="BranchNum" :formatter="dataFormat1" label="所在机构名称"></el-table-column>
        <el-table-column prop="PhoneNum"  label="手机"></el-table-column>
        <el-table-column prop="UserLevel" :formatter="dataFormat" label="用户级别"></el-table-column>
        <!-- <el-table-column prop="usertype"  label="用户类型"></el-table-column> -->
        <!-- <el-table-column prop="certtp" :formatter="dataFormat" label="认证方式"></el-table-column> -->
      </el-table>
      <div style="text-align:right;margin-top:20px;" v-show="this.tableData">
        <el-pagination  :current-page="currentPage" background
          :page-size="pageSize"
          layout="total, prev, pager, next, jumper"
          :total="totalRcrdNum"
          @current-change="changePage">
        </el-pagination>
      </div>
    </el-card>
    <!-- 弹窗 -->
    <keep-alive>
      <component :is="dialogList.CreateUser" :option="dialogOptions" @refreshTable="checkUserList()"></component>
    </keep-alive>
    <!-- 用户应用分配 -->
     <keep-alive>
      <component :is="dialogList.appOpenDialog" :option="dialogOptionsSystem"   @systemEmit="checkUserList()"></component>
    </keep-alive>
     <keep-alive>
      <component :is="dialogList.casherPostDialog" :option="dialogOptionsCasherPost"   @systemEmit="checkUserList()"></component>
    </keep-alive>
     <keep-alive>
      <component :is="dialogList.branchDistributionDialog" :option="dialogOptionsBranchDistribution"   @systemEmit="checkUserList()"></component>
    </keep-alive>
    <keep-alive>
      <component :is="dialogList.updateUser" :optionUpdate="dialogOptionsupdateUser"  @refreshTable="checkUserList()"></component>
    </keep-alive>
    <keep-alive>
      <component :is="dialogList.changUserBranch" :optionUpdate="dialogOptionschangUserBranch"  @refreshTable="checkUserList()"></component>
    </keep-alive>
  </div>
</template>

<script>
import selectTree from "@/components/selectTree3/";
import request from "@/common/utils/request";
import getGlobalParams from "@/common/utils/getGlobalParams";
import toolBox from "@/common/utils/toolBox";
import CreateUser from "./dialog/CreateUser";
import updateUser from "./dialog/updateUser";
import changUserBranch from "./dialog/userBranchChang";
import appOpenDialog from "./dialog/appOpen";
import casherPostDialog from "./dialog/casherPost";
import branchDistributionDialog from "./dialog/branchDistribution";

import InquireUser from "@/message/userManage/user/inquire-user";
import userDel from "@/message/userManage/user/user-del";
import branchList from "@/message/shared/branch-list";
import resetPassword from "@/message/userManage/user/reset-password";
import userUnlock from "@/message/userManage/user/user-unlock";

export default {
  name: "user-info-manage",
  components: { selectTree },
  data() {
    return {
      userState: {}, //用户状态
      userLevel: {}, //用级级别
      pageSize: undefined, //表格每页的条数
      brnoList: [], //机构下拉列表数据
      brnoName: {},
      brnoMap: {},
      certtp : {
        "0":"密码",
        "2":"指纹"
      },
      form: {
        //表单数据
        ID: "",
        name: "",
        branchId: [],
        // usertype:""
      },
      usertypeList: [
        { label: "V端用户",value: "0" },
        {label: "C端用户",value: "1"}
      ],
      form1: {},
      currentRow: [], //表格当前选中行
      currentPage: 1, //表格当前页
      totalRcrdNum: 0,
      tableData: [], //表格 数据
      dialogList: {
        //指定被渲染组件列表
        CreateUser,
        appOpenDialog,
        casherPostDialog,
        branchDistributionDialog,
        updateUser,
        changUserBranch
      },
      dialogOptions: {
        //创建用户
        isShow: false
      },
      dialogOptionsSystem: {
        //用户所属系统
        isShow: false,
        currentRow: []
      },
      dialogOptionsCasherPost: {
        //柜员岗位设置
        isShow: false,
        currentRow: []
      },
      dialogOptionsBranchDistribution: {
        //业务机构分配
        isShow: false,
        currentRow: []
      },
      dialogOptionsupdateUser: { isShow: false, currentRow: [] }, //修改用户
      dialogOptionschangUserBranch: { isShow: false, currentRow: [] }, //机构调动
      loading: false, //loading遮罩
      total: 0, //表格总条数
      startDialogVisible: false,
      checkedUser: false, //控制按钮是否可用
      isDisabledDel: false
    };
  },
  computed: {
    tableDataPage() {
      //实现前端分页
      return this.tableData;
    }
  },
  created() {
    //初始化下拉框
    this.userState = getGlobalParams.get("userState"); //用户状态初始化
    this.userLevel = getGlobalParams.get("userLevel"); //用户级别初始化
    console.log(this.userLevel);
    let resBody = new branchList();
    resBody.data.orgno = this.$store.getters.BranchNum;
    request(resBody)
      .then(response => {
          this.brnoList = response.RspInfo.Result || [];
          this.brnoMap = response.RspInfo.orgMap || {};
          this.brnoList = toolBox.formatTreeData(
            this.brnoList,
            "orgno",
            "superno"
          );
        this.checkUserList();
      })
      .catch(error => {
        console.error("错误信息", error);
      });
    this.pageSize = getGlobalParams.get("PageSize");
  },
  methods: {
    changePage(val) {
      //表格换页改变currengPage的值
      this.currentPage = val;
      this.checkUserList(val,true);
    },
    delUser() {
      //删除弹出
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.userDel();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    dataFormat(row, column) {
      //格式化表格
      //枚举设备形式
      if (column.property == "UserStatus")
        return this.userState[row[column.property]];
      if (column.property == "UserLevel")
        return this.userLevel[row[column.property]];
      // if (column.property == "BranchName")
      //   return this.brnoName[row["BranchNum"]];
      if (column.property == "certtp")
        return this.certtp[row[column.property]];
    },
    dataFormat1(row, column){
      if (column.property == "BranchNum")
        return  this.brnoMap[row[column.property]];

    },
    resetForm(formName) {
      //重置查询表单
      this.$refs["" + formName].resetFields();
    },
    handleCommand(val) {
      //更多操作按钮的切换
      if (val == "systemUser") {
        this.systemUser();
      } else if (val == "unlock") {
        this.unlock();
      } else if (val == "changBranch") {
        this.userBranchChang();
      } else if (val == "casherPost") {
        this.casherPost();
      } else if (val == "branchDistribution") {
        this.branchDistribution();
      }
    },
    createUser() {
      //改变创建用户的显示状态
      this.dialogOptions.isShow = true;
    },
    systemUser() {
      //用户应用分配
      this.dialogOptionsSystem.isShow = true;
      this.dialogOptionsSystem.currentRow = this.currentRow;
    },
    casherPost() {
      //柜员岗位设置
      this.dialogOptionsCasherPost.isShow = true;
      this.dialogOptionsCasherPost.currentRow = this.currentRow;
    },
    branchDistribution() {
      //业务机构分配
      this.dialogOptionsBranchDistribution.isShow = true;
      this.dialogOptionsBranchDistribution.currentRow = this.currentRow;
    },
    modUser() {
      //修改用户
      this.dialogOptionsupdateUser.isShow = true;
      this.dialogOptionsupdateUser.currentRow = this.currentRow;
    },
    userBranchChang() {
      //修改机构
      this.dialogOptionschangUserBranch.isShow = true;
      this.dialogOptionschangUserBranch.currentRow = this.currentRow;
    },
    userDel() {
      //删除用户
      this.loading = true;
      let resBody = new userDel();
      resBody.data.userId = this.currentRow.UserID;
      request(resBody)
        .then(response => {
          if (response.SYS_HEAD.ReturnCode === "000000") {
            this.loading = false;
            this.$message({
              type: "success",
              message: "用户删除成功!"
            });
            this.checkUserList();
          } else {
            this.loading = false;
            this.$message({
              type: "success",
              message: "用户删除失败!"
            });
          }
        })
        .catch(error => {
          this.loading = false;
        });
    },
    //用户解锁
    unlock() {
      this.$confirm("此操作将解锁用户登录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          //
          this.loading = true;
          let resBody = new userUnlock();
          resBody.data.UserNum = this.currentRow.UserNum;
          request(resBody)
            .then(response => {
              if (response.SYS_HEAD.ReturnCode === "000000") {
                this.loading = false;
                this.$message({
                  type: "success",
                  message: "解锁用户成功"
                });
              } else {
                this.loading = false;
                this.$message({
                  type: "warning",
                  message: "解锁用户失败," + response.SYS_HEAD.ReturnMessage
                });
              }
            })
            .catch(error => {
              this.loading = false;
            });
          //
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消重置"
          });
        });
    },
    checkUserList(val = 1,isPage) {
      if(!isPage){
      this.currentPage = val
      this.form1 = Object.assign({}, this.form)
      console.log(this.form1)
      }
      //查询用户表格
      this.tableData = [];
      this.checkedUser = false;
      this.isDisabledDel = false;
      this.loading = true;
      let resBody = new InquireUser();
      resBody.data.Tlr = this.form1.ID;
      resBody.data.TlrNm = this.form1.name;
      resBody.data.BrahNumC = this.form1.branchId[0];
      resBody.data.StartRows = (this.currentPage - 1) * this.pageSize;
      resBody.data.PageSize = this.pageSize;
      resBody.data.CurtPage = this.currentPage;
      if (
        this.form1.ID == "" &&
        this.form1.name == "" &&
        this.form1.branchId == ""
      ) {
        resBody.data.BrahNumC = this.$store.getters.BranchNum;
        resBody.TransServiceCode = "UPMS_TV005";
      }
      request(resBody)
        .then(response => {
           this.totalRcrdNum = response.RspInfo.TotalRcrdNum
          ? response.RspInfo.TotalRcrdNum
          : 0;
          if (response.SYS_HEAD.ReturnCode === "000000") {
            //  console.log(response.RSP_BODY.UserList,"response.RSP_BODY.UserList")
            let Result = response.RspInfo.Result || [];
            Result.forEach(element => {
              // if (element.UserNum != "admin") {
                this.tableData.push(element);
              // }
            });
          } else {
            this.tableData=[];
            this.$message({
              type: "info",
              message: response.SYS_HEAD.ReturnMessage
            });
          }
          this.loading = false;
          // let list=response.RSP_BODY.roleInfoList
          // for(let i=0;i<list.length;i++){
          //    list[i].UserState=="0"? list[i].UserState="失效":(list[i].UserState=="1"?list[i].UserState="正常":list[i].UserState="锁定")
          // }
          // this.tableData =list;
        })
        .catch(error => {
          this.loading = false;
          // this.logger.log("fail", error);
        });
    },
    handleCurrentChange(val) {
      //表格选中行改变事件设置当前行的值（currentRow）已经改变控制按钮是否可用
      this.currentRow = val[0];
      if (val.length == 1) {
        this.checkedUser = true;
        this.isDisabledDel = true;
      } else if (val.length > 1) {
        this.checkedUser = false;
        this.isDisabledDel = true;
      } else {
        this.checkedUser = false;
        this.isDisabledDel = false;
      }
    },

    /**
     * @desc 手动重置密码
     */
    handleResetPassword() {
      this.$confirm("此操作将重置此用户密码为123456, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.resetPassword();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消重置"
          });
        });
    },

    /**
     * @desc 重置密码通讯方法
     * @param userId
     */
    resetPassword() {
      this.loading = true;
      let resBody = new resetPassword();
      resBody.data.UserNum = this.currentRow.UserNum;
      request(resBody)
        .then(response => {
          if (response.SYS_HEAD.ReturnCode === "000000") {
            this.loading = false;
            this.$message({
              type: "success",
              message: "密码重置成功"
            });
          } else {
            this.loading = false;
            this.$message({
              type: "error",
              message: "密码重置失败"
            });
          }
        })
        .catch(error => {
          this.loading = false;
        });
    }
  }
};
</script>


<style lang="scss" scoped>
.selectTree {
  min-width: 150px;
}
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}
.dialog-text {
  display: inline-block;
  width: 100%;
  text-align: center;
  color: red;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

.el-card {
  width: 100%;
}
.el-form-item {
  margin-left: 30px;
}
.el-form-item1 {
  margin-left: 10px;
}
.box2-button {
  width: 80px;
}

.el-card {
  overflow: inherit;
}
</style>
